/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.util;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 
 * @author haolw
 * @time 2017/09/08
 */
public abstract class QRCodeUtil {
	protected static final int PIXEL = 43;
	protected static final int DEFAULT_RATE = 6;
	private static final Map<EncodeHintType, Object> hints;
	static {
		hints = new HashMap<EncodeHintType, Object>();
		// 指定纠错等级,纠错级别（L 7%、M 15%、Q 25%、H 30%）
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		hints.put(EncodeHintType.MARGIN, 1);// 设置二维码边的空度，非负数整数
	}

	/**
	 * 创建二维码图片 默认倍率：6，QR.width:258,height:258
	 * 
	 * @param rate
	 * @param content
	 * @return
	 */
	public static BufferedImage creatQRImage(String content) {
		return creatQRImage(null, content);
	}

	/**
	 * 创建二维码图片 默认倍率：6，QR.width:258,height:258
	 * 
	 * @param rate
	 * @param content
	 * @return
	 */
	public static BufferedImage creatQRImage(Integer rate, String content) {
		BufferedImage QRImage;
		try {
			if (rate == null) {
				rate = DEFAULT_RATE;
			}
			int length = PIXEL * rate;
			BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, length, length, hints);
			QRImage = MatrixToImageWriter.toBufferedImage(matrix);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return QRImage;
	}
}
